<?php
/**
 * This is the template for generating a controller class file for CRUD feature.
 * The following variables are available in this template:
 * - $this: the CrudCode object
 */
?>
<?php echo "<?php\n"; ?>

class <?php echo $this->controllerClass; ?> extends <?php echo $this->baseControllerClass."\n"; ?>
{

	/**
	 * 创建
	 */
	public function actionCreate()
	{
		$model=new <?php echo $this->modelClass; ?>;

		// 要开启 AJAX 验证，去掉下行注释
		// $this->performAjaxValidation($model);

		if(isset($_POST['<?php echo $this->modelClass; ?>']))
		{
			$model->attributes=$_POST['<?php echo $this->modelClass; ?>'];
			if($model->save())
				$this->redirect(array('admin'));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * 编辑
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// 要开启 AJAX 验证，去掉下行注释
		// $this->performAjaxValidation($model);

		if(isset($_POST['<?php echo $this->modelClass; ?>']))
		{
			$model->attributes=$_POST['<?php echo $this->modelClass; ?>'];
			if($model->save())
				$this->redirect(array('admin'));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}
	
	/**
	 *单条，批量删除
	 *传入参数，$GET单条，$POST批量
	 */
	public function actionDelete(){
		//操作ID号格式处理
		if(isset($_GET['id'])){
			$id = $_GET['id'];
		}elseif(isset($_POST['ids'])){
			$id =$_POST['ids'];
		}else{
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}

		//处理条件
		$criteria=new CDbCriteria;
		$criteria->addInCondition("<?php echo $this->tableSchema->primaryKey ?>",(array)$id);

		//执行操作
		if(<?php echo $this->modelClass; ?>::model()->deleteAll($criteria)){
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
	}
	
	/**
	 * 管理.
	 */
	public function actionAdmin()
	{
		$model=new <?php echo $this->modelClass; ?>('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['<?php echo $this->modelClass; ?>']))
			$model->attributes=$_GET['<?php echo $this->modelClass; ?>'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * 根据主键，载入模型，如果找不到相关数据，跳转到404页面
	 * @param integer the ID 
	 */
	public function loadModel($id)
	{
		$model=<?php echo $this->modelClass; ?>::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * AJAX验证
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='<?php echo $this->class2id($this->modelClass); ?>-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
